<template>
  <div>
    <div class="g-cur">
      <div class="wp">
        <NuxtLink to="/" class="a">创作中心</NuxtLink><span> / </span>
        <span class="s">创建作品</span>
      </div>
    </div>
    <div class="wp">
      <div class="createW">
        <!-- tab -->
        <ul class="ul-steps">
          <li class="act">
            <div class="idx">1</div>
            <div class="p">书籍信息</div>
          </li>
          <li >
            <div class="idx">2</div>
            <div class="p">版权信息</div>
          </li>
          <li >
            <div class="idx">3</div>
            <div class="p">打印信息</div>
          </li>
          <li >
            <div class="idx">4</div>
            <div class="p">价格信息</div>
          </li>
        </ul>
        <!-- 内容 -->
        <div class="m-bookInfol">
          <div class="m-forml1">
            <a-form>
              <div class="item">
                <a-form-item label="书籍类型" class="keynote">
                  <ul class="ul-listl3">
                    <li :class="{ on: index === act }" v-for="(item, index) in listl1" :key="index"
                      @click="act = index; formState.type = item.key">
                      <div class="con">
                        <div class="pic">
                          <div class="img" :style="'background-image: url(' + item.src + ');'"></div>
                        </div>
                        <div class="txt">
                          <div class="dot"></div>
                          <div class="tit">{{ item.tit }}</div>
                          <div class="desc">{{ item.desc }}</div>
                        </div>
                      </div>
                    </li>
                  </ul>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="书籍名称" class="keynote">
                  <a-input v-model:value="formState.title" class="inp" placeholder="请输入书籍名称" />
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item class="it2 keynote" label="书籍语言">
                  <div class="m-selectl">
                    <a-select ref="select" v-model:value="formState.language" placeholder="选择书籍语言" style="width: 205px">
                      <a-select-option v-for="(item, index) in types.language" :key="index" :value="item">{{ item
                        }}</a-select-option>
                    </a-select>
                  </div>
                </a-form-item>
                <a-form-item class="it2 keynote" label="书籍分类">
                  <div class="m-selectl">
                    <a-select ref="select" v-model:value="formState.category" placeholder="选择书籍分类" style="width: 205px">
                      <a-select-option v-for="(item, index) in types.category" :key="index" :value="item">{{ item
                        }}</a-select-option>
                    </a-select>
                  </div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="Bisac主要类别" class="keynote">
                  <div class="m-selectl">
                    <a-select ref="select" v-model:value="formState.bisacMainCategory" placeholder="选择类别"
                      style="width: 205px">
                      <a-select-option value="A">金浆果</a-select-option>
                      <a-select-option value="B">银浆果</a-select-option>
                      <a-select-option value="C">铜浆果</a-select-option>
                    </a-select>
                  </div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="关键字" class="keynote">
                  <a-input v-model:value="formState.keywords" class="inp" placeholder="请输入关键字" />
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="选择受众" class="keynote">
                  <div class="m-selectl">
                    <a-select ref="select" v-model:value="formState.audience" placeholder="选择受众" style="width: 200px">
                      <a-select-option v-for="(item, index) in types.audiences" :key="index" :value="item">{{ item
                        }}</a-select-option>
                    </a-select>
                  </div>
                  <a-checkbox v-model:checked="checked" class="checkbox">本书是否包含露骨内容</a-checkbox>
                  <div v-if="checked" class="m-selectl">
                    <a-select ref="select" v-model:value="formState.audience" placeholder="选择受众" style="width: 200px">
                      <a-select-option v-for="(item, index) in types.audiences" :key="index" :value="item">{{ item
                        }}</a-select-option>
                    </a-select>
                  </div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="书籍封面图" class="keynote">
                  <div class="upload1">
                    <a-upload :auto-upload="false" v-model:file-list="fileList1" :beforeUpload="handleChangeImg" list-type="picture-card"
                    @remove="removeFile"
                      @preview="handlePreview">
                      <div>
                        <plus-outlined />
                      </div>
                    </a-upload>
                    <a-modal :visible="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
                      <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                  </div>
                  <div class="tips">请上传书籍封面用于网页前端展示，提升发布效率。建议尺寸：800*800 像素，最大不超过50M</div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="贡献者信息" class="keynote">
                  <div class="m-contributorl">
                    <div class="contribox" v-for="(item, index) in formState?.contributors?.filter(i => i.status != 2)"
                      :key="index">
                      <div class="box">
                        <div class="ll">角色类型：</div>
                        <div class="rr">
                          <a-select ref="select" v-model:value="item.role" placeholder="选择角色类型">
                            <a-select-option v-for="(item1, index1) in types.contributor" :key="index1"
                              :value="item1">{{ item1 }}</a-select-option>
                          </a-select>
                        </div>
                      </div>
                      <div class="box">
                        <div class="ll">名：</div>
                        <div class="rr">
                          <a-input v-model:value="item.firstname" class="inp" placeholder="请输入名字" />
                        </div>
                      </div>
                      <div class="box">
                        <div class="ll">姓氏：</div>
                        <div class="rr">
                          <a-input v-model:value="item.lastname" class="inp" placeholder="请输入姓氏" />
                        </div>
                      </div>
                      <div class="add">
                        <div @click="deleteUser(item, index)" class="icon"><img src="/images/iconl8.png" alt=""></div>
                        <div @click="addUser()" class="icon"><img src="/images/iconl9.png" alt=""></div>
                      </div>
                    </div>
                  </div>
                  <div class="tips">添加本书每个贡献者的姓名和角色，包括你要感谢的本书作者、编辑和插图画家，最多展示5位</div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="书籍简介" class="keynote">
                  <div class="text">
                    <a-textarea placeholder="请输入书籍作品的描述" v-model:value="formState.description" class="textarea" />
                    <div class="num">0/2500</div>
                  </div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="书籍目录">
                  <div class="text">
                    <a-textarea placeholder="使用逗号分隔列表为图书添加目录。此处输入的目录可帮助用户了解书籍部分内容。"
                      v-model:value="formState.tableOfContents" class="textarea" />
                    <div class="num">0/2500</div>
                  </div>
                </a-form-item>
              </div>
              <div class="item">
                <a-form-item label="贡献者说明">
                  <div class="text">
                    <a-textarea placeholder="添加有关作品贡献者的信息，例如相关作品、网站、社交媒体资料和其他显著成就，"
                      v-model:value="formState.contributorNotes" class="textarea" />
                    <div class="num">0/2500</div>
                  </div>
                </a-form-item>
              </div>
              <div class="bot-opts">
                <NuxtLink to="/myWorks" class="btn">取消</NuxtLink>
                <a @click="saveBooks()" class="btn btn1">下一步</a>
              </div>
            </a-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import request from '~/services/request'
import { message } from 'ant-design-vue';
import { RouterLink, RouterView, useRouter } from 'vue-router'
const router = useRouter()
const route = useRoute()
const id = ref(route.query.id)


const S3 = ref(null)


const act = ref(0);
const value1 = ref();
const value2 = ref();
const value3 = ref();
const value4 = ref();
const value5 = ref();
const value6 = ref();
const checked = ref(false);
const formState = reactive({
  title: '',
  language: '',
  category: '',
  type: 'PRINT_BOOK',
  // subtitle: '',
  // edition: '',
  // editionStatement: '',
  bannerImages: [],
  description: '',
  contributorNotes: '',
  tableOfContents: '',
  keywords: '',
  bisacMainCategory: '',
  // bisacCategory2: '',
  // bisacCategory3: '',
  audience: '',
  // explicitContentType: '',
  contributors: [{
    firstname: '',
    lastname: '',
    role: '',
    status: 0,
  }],
});
function addUser() {
  if (formState.contributors.length == 5) {
    message.error({
      content: () => '只能添加5个！',
      class: 'custom-class',
      style: {
        marginTop: '20vh',
      },
    });
    return false
  }
  formState.contributors.push(
    {
      firstname: '',
      lastname: '',
      role: '',
      status: '0'
    }
  )
}
function deleteUser(item, index) {
  if (formState.contributors.length == 1) {
    message.error({
      content: () => '至少需要一个！',
      class: 'custom-class',
      style: {
        marginTop: '20vh',
      },
    });
    return false
  }
  if (item.status == 1) {
    item.status = 2
  }
  if (item.status == 0) {
    formState.contributors = formState.contributors.filter(item => (formState.contributors.findIndex(obj => obj == item)) !== index)
  }
  // formState.contributors.slice(index,1)
}
const types = ref({})
const listl1 = reactive([
  {
    src: '/images/imgl3.jpg',
    tit: '印刷书籍',
    key: 'PRINT_BOOK',
    desc: '精装或平装书使用多种纸张、颜色和装订选项。最常见的按需印刷书籍，非常适合各种项目。',
  }, {
    src: '/images/imgl4.jpg',
    tit: '写真集',
    key: 'PHOTO_BOOK',
    desc: '使用精装相册保存回忆或创建作品集。我们的相册采用最高品质的纸张和丰富的彩色墨水，突出了 Lulu 的最佳印刷选项。',
  }, {
    src: '/images/imgl5.jpg',
    tit: '漫画',
    key: 'COMIC_BOOK',
    desc: '传统漫画书尺寸，平装。使用黑白或丰富色彩打印（包括封面内页）让您的艺术作品栩栩如生。',
  }, {
    src: '/images/imgl6.jpg',
    tit: '杂志',
    key: 'MAGAZINE',
    desc: '制作色彩鲜艳、装订精美的杂志，装订成平装本。采用专为杂志设计的纸张，并在封面内侧进行印刷。',
  }
]);
function saveBooks() {
  for (const key in formState) {
    if (Object.hasOwnProperty.call(formState, key)) {
      if (!formState[key]&&key!='tableOfContents'&&key!='contributorNotes') {
        message.error({
          content: () => '*为必填项！',
          class: 'custom-class',
          style: {
            marginTop: '20vh',
          },
        });
        return false;
      }
    }
  }
  debugger
  if (id.value) {
    let deletes = []
    let updates = []
    let creates = []
    formState.contributors.forEach(item => {
      if (item.status == 2) {
        deletes.push({
          id: item.id,
        })
      }
      if (item.status == 1) {
        updates.push({
          firstname: item.firstname,
          lastname: item.lastname,
          role: item.role,
          id:item.id

        })
      }
      if (item.status == 0) {
        creates.push({
          firstname: item.firstname,
          lastname: item.lastname,
          role: item.role,

        })
      }
    })
    formState.contributors = {
      delete: deletes,
      create: creates,
      update: updates
    }
  }else{
    formState.contributors.forEach(val=>{
      delete val.status;
    })
  }
  if (id.value) {
    formState.id = id.value
    request.patch_books_by_id(formState).then(res => {

      router.push('/copyright?id=' + res.id + '&from=1');
    })
  } else {
    request.create_books(formState).then(res => {

      router.push('/copyright?id=' + res.id + '&from=1');
    })
  }
}

// 上传图片
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
var albumBucketName = ref("silentberry.co");
var bucketRegion = "ap-northeast-1";
var IdentityPoolId = "mmlE8+vSEaPwMqR9WxFCcCO+xqxPfWEC17qSKXKY";
const fileList1 = ref([]);
const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
function removeFile(file){
  debugger
formState.bannerImages.splice(formState.bannerImages.findIndex(item=>item==file.url),1)
}
const handlePreview = async file => {
  debugger
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};
async function handleChangeImg(file) {
  const uploadResult = await S3.value.putObject({
    Bucket: 'silentberry.co',
    Key: file.uid,
    Body: file,
    ContentType: file.type
  }).promise()
  formState.bannerImages.push('https://s3.ap-northeast-1.amazonaws.com/silentberry.co/'+file.uid)
  return false
}

onMounted(() => {
  if (id.value) {
    request.get_books_my_by_id({ id: id.value }).then(res => {
      for (const key in formState) {
        if (Object.hasOwnProperty.call(formState, key)) {
          formState[key] = res[key];
        }
      }
      formState.bannerImages.forEach(key => {
          fileList1.value.push(
          {
            uid: Math.random(),
            status: 'done',
            url: key,
          }
        )

      })
      formState.contributors.forEach(val => {
        val.status = 1
      })
    })
  }
  let script = document.createElement('script');
  script.src = '/aws-sdk-2.1673.0.min.js';
  script.onload = () => {
    // 脚本加载完毕后的回调
    AWS.config.update({
      accessKeyId: 'AKIA23OJK3X3H2OI5MLV',
      secretAccessKey: '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',
      region: 'ap-northeast-1'
    })

    S3.value = new AWS.S3({
      apiVersion: "2006-03-01",
      params: { Bucket: 'silentberry.co' }
    })
  };
  document.body.appendChild(script);
  request.api_config({ id: 'all' }).then(res => {
    types.value = res
  })
})
</script>

<style></style>